(function($) {
	$.entwine('ss', function($) {
		// start modal div
		var content = '<div id="member_detail_modal"></div>';
		$('body').append(content);

		var $member_detail_modal = $('#member_detail_modal');
		$member_detail_modal.dialog({
			resizable : false,
			modal : true,
			autoOpen : false,
			width: 500
		});
		
		var loading = function(action){
			if(action == 'start'){
				$('.cms-content').addClass('loading');
			} else {
				$('.cms-content').removeClass('loading');
			}
		};
		
		$('#Sponsor').entwine({
			onmatch: function(){
				var self = this;
				var option = { 
		            // List of active plugins
		            "plugins" : [ 
		                "themes","json_data","ui","search","types"
		            ],
		            'themes': {
						'theme': 'apple',
						'url': $('body').data('frameworkpath') + '/thirdparty/jstree/themes/apple/style.css'
					},
		            // I usually configure the plugin that handles the data first
		            // This example uses JSON as it is most common
		            "json_data" : { 
		                "data" : [],
		                // This tree is ajax enabled - as this is most common, and maybe a bit more complex
		                // All the options are almost the same as jQuery's AJAX (read the docs)
		                "ajax" : {
		                    "type" : "GET",
		                    "global" : false,
		                    // the URL to fetch the data
		                    "url" : self.data('load-link'),
		                    // the `data` function is executed in the instance's scope
		                    // the parameter is the node being loaded 
		                    // (may be -1, 0, or undefined when loading the root nodes)
		                    "data" : function (n) { 
		                        // the result is fed to the AJAX request `data` option
		                        return { 
		                            "operation" : "GetChildren", 
		                            "id" : n.attr ? n.attr("id").replace("node_","") : 1 
		                        }; 
		                    }
		                }
		                
		            },
		            // Configuring the search plugin
		            "search" : {
		                // As this has been a common question - async search
		                // Same as above - the `ajax` config option is actually jQuery's AJAX object
		                "ajax" : {
		                    "type" : "GET",
		                    "global" : false,
		                    "url" : self.data('load-link'),
		                    // You get the search string as a parameter
		                    "data" : function (str) {
		                        return { 
		                            "operation" : "Search", 
		                            "id" : str 
		                        }; 
		                    }
		                }
		            },
		            // Using types - most of the time this is an overkill
		            // read the docs carefully to decide whether you need types
					"types" : {
						"types" : {
							// The default type
							"default" : {
								// If we specify an icon for the default type it WILL OVERRIDE the theme icons
								"icon" : {
									"image" : "network/images/tree/default.png"
								}
							}
						}
					},
		            // the core plugin - not many options here
		            "core" : { 
		                // just open those two nodes up
		                // as this is an AJAX enabled tree, both will be downloaded from the server
		                "initially_open" : [],
		                "html_titles" : true,
		                "select_limit" : 1
					}
				};
				
				var buildJSTree = function(root_data, root_id){
					option.json_data.data = root_data;
					option.json_data.ajax.data = function (n) { 
                        // the result is fed to the AJAX request `data` option
                        return { 
                            "operation" : "GetChildren", 
                            "id" : n.attr ? n.attr("id").replace("node_","") : root_id 
                        }; 
                   	};
                   	option.core.initially_open = [ root_id ];
                   	$("#sponsor_tree").jstree('destroy');
			        $("#sponsor_tree").jstree(option)
			        .bind("search.jstree", function (e, data) {
			            data.rslt.nodes.find("span").addClass("search");
			        })
			        .bind("clear_search.jstree", function (e, data) {
			            data.rslt.find("span").removeClass("search");
			        })
			        .bind("select_node.jstree", function (e, data) {
			        	if(data.rslt.obj.data("ID") > 0 && data.rslt.obj.data("ID") != undefined){
			        		var url = self.data('member-link');
							loading('start');
							$.get(url, {'id': data.rslt.obj.data("ID")}, function(data) {
								$member_detail_modal.html(data);
								$member_detail_modal.dialog("option", "buttons", []);
								$member_detail_modal.dialog('open');
							}).fail(function() {
								$member_detail_modal.html('<p>' + ss.i18n._t('NetworkAdmin.ERROR_LOADING_MEMBER_DETAILS', 'Error occur while load member details, please try again.') +'</p>');
								$member_detail_modal.dialog("option", "buttons", []);
								$member_detail_modal.dialog('open');
							}).always(function() {
			    				loading('end');
			  				});
				
							e.preventDefault();
			        	}
			        });
				};
				
				loading('start');
				$.getJSON(self.data('default-link'), function(json) {
					if(json.result == 'success'){
						buildJSTree(json.root, json.root.attr.id);
				        
				        $("#treemenu").find('a').live('click', function(e) {
				        	e.preventDefault();
							switch(this.id) {
								case "sponsor_search":
									loading('start');
									var username = $("#sponsor_search_text").val();
									if(username != '' && username != undefined){
										$.getJSON(self.data('default-link'), {'username': username}, function(json) {
											if(json.result == 'success'){
												buildJSTree(json.root, json.root.attr.id);
									        }
									        else{
									        	alert(json.msg);
									        }
										}).fail(function() {
											alert(ss.i18n._t('NetworkAdmin.ERROR_LOADING_TREE', 'Error occur while load these tree, please try again.'));
										}).always(function() {
						    				loading('end');
						  				});
					  				}
									break;
								case "sponsor_clear_search":
									$("#sponsor_search_text").val('');
									loading('start');
									$.getJSON(self.data('default-link'), function(json) {
										if(json.result == 'success'){
											buildJSTree(json.root, json.root.attr.id);
								        }
								        else{
								        	alert(json.msg);
								        }
									}).fail(function() {
										alert(ss.i18n._t('NetworkAdmin.ERROR_LOADING_TREE', 'Error occur while load these tree, please try again.'));
									}).always(function() {
					    				loading('end');
					  				});
									break;
								case "sponsor_refresh":
									$("#sponsor_tree").jstree("deselect_node");
									$("#sponsor_tree").jstree("refresh");
									break;
								case "sponsor_open_all":
									$("#sponsor_tree").jstree("open_all");
									break;
								case "sponsor_close_all":
									$("#sponsor_tree").jstree("close_all");
									break;
								case "sponsor_search_text": break;
								default:
									$("#sponsor_tree").jstree(this.id);
									break;
							}
						});
					}
					else{
						alert(json.msg);
					}
			    }).fail(function() {
					alert(ss.i18n._t('NetworkAdmin.ERROR_LOADING_TREE', 'Error occur while load these tree, please try again.'));
				}).always(function() {
					loading('end');
				});
			}
		});
		
		$('#Placement').entwine({
			onmatch: function(){
				var self = this;
				self.tooltip();
				var doRefreshTree = function(username, link) {
					$member_detail_modal.dialog('close');
					loading('start');
					$.getJSON(link, {
						'username' : username
					}, function(data) {
						if (data.error != '' && data.error != undefined) {
							alert(data.error);
						}
						else {
							$('#placement_tree').html(data.result);
						}
					}).fail(function() {
						alert(ss.i18n._t('NetworkAdmin.ERROR_LOADING_TREE', 'Error occur while load these tree, please try again.'));
					}).always(function() {
		    			loading('end');
		  			});
				};
		
				$('#placement_search_tree').entwine({
					onmatch: function(){
			          	doRefreshTree($('#placement_search_text').val(), this.data('link'));
			       	},
					onclick: function(e) {
						var username = $('#placement_search_text').val();
						if (username != '' && username != undefined) {
							doRefreshTree(username, this.data('link'));
						}
						e.preventDefault();
					}
				});
		
				$('#previous').entwine({
					onclick: function(e) {
						var username = this.data('username');
						if (username != '' && username != undefined) {
							$('#placement_search_text').val(username);
							doRefreshTree(username, $('#placement_search_tree').data('link'));
						}
						e.preventDefault();
					}
				});
		
				$('.member_detail').entwine({
					onclick: function(e) {
						var url = this.attr('href');
						var username = $(this).data('username');
						loading('start');
						$.get(url, function(data) {
							$member_detail_modal.html(data);
							$member_detail_modal.dialog("option", "buttons", [{
								text : $('#placement_tree').data('view-team-button'),
								click : function() {
									$('#placement_search_text').val(username);
									doRefreshTree(username, $('#placement_search_tree').data('link'));
								}
							}]);
							$member_detail_modal.dialog('open');
						}).fail(function() {
								$member_detail_modal.html('<p>' + ss.i18n._t('NetworkAdmin.ERROR_LOADING_MEMBER_DETAILS', 'Error occur while load member details, please try again.') +'</p>');
								$member_detail_modal.dialog("option", "buttons", []);
								$member_detail_modal.dialog('open');
						}).always(function() {
		    				loading('end');
		  				});
			
						e.preventDefault();
					}
				});
				
				$('a.view_tree').entwine({
					onclick: function(e) {
						var username = $(this).data('username');
						if (username != '' && username != undefined) {
							$('#placement_search_text').val(username);
							doRefreshTree(username, $('#placement_search_tree').data('link'));
						}
						e.preventDefault();
					}
				});
			}
		});
	});
})(jQuery); 